#!/usr/bin/python
import htmllib
import formatter
import urllib2

'''
GenericParser provides a base class for parsing and downloading

_get_slash_number(self)
_url_is_picture(self,url)
_get_picture_path(self,picture)
_get_current_thread_url(self)

needs to be implemented in a subclass
'''

class Parser(htmllib.HTMLParser):
        def __init__(self):
            htmllib.HTMLParser.__init__(self,formatter.NullFormatter())
            self.p = None
        def anchor_bgn(self, href, name, type):
            if self.p._url_is_picture(href) and href not in self.p.urls:
                self.p.urls.append(href) 

class GenericParse():

    
    
    def __init__(self):
        self.__parser = Parser()
        self.__parser.p = self
        self.board = None
        self.thread = None
        self.urls = []
        self.error = None
        
    '''
    number of / in an image url
    '''
    def _get_slash_number(self):
        return None

    '''
    return true if the url is a valid picture
    otherwise false
    '''
    def _url_is_picture(self,url):
        return None
    '''
    get the string 
    '''
    def _get_picture_path(self,picture):
        return None

    '''
    get url of the current thread
    '''
    def _get_current_thread_url(self):
        return None

    '''
    synchronize with thread
    '''
    def sync(self):
        try:
            url = self._get_current_thread_url()
            print 'get %s' % url
            f = urllib2.urlopen(url)
            raw = f.read()
            f.close()
            self.__parser.feed(raw)
        except Exception as err:
            self.error = str(err)
            return False
        return True

    '''
    download all pictures in thread
    '''
    def download(self):
        for pic in self.urls:
            print "downloading %s" % pic
            try:
                rem = urllib2.urlopen(pic)
                loc = open(pic.split('/')[self._get_slash_number()],'w')
                loc.write(rem.read())
                loc.close()
                rem.close()
            except Exception as err:
                self.error = str(err)
                return False
        return True
